import tornado.web
import tornado.ioloop
import tornado.websocket
import time

class EchoWebSocket(tornado.websocket.WebSocketHandler):
	# room是形如 {'TestRoom':{'张飞':[1, Obj], '刘备':[0, Obj]}, 
	#			  'NewRoom':{'曹操':[0, Obj], '曹植':[1,Obj]} }
	# 的一个字典对象，其中Obj是一个EchoWebSocket对象, 数字表示该用户发送消息的次数。

	room = {}
	roomname = ''
	nick = ''

	def open(self):
		self.roomname = self.get_argument("room") 
		self.nick = self.get_argument("nick") 
		if self.roomname in self.room.keys():
			self.room[self.roomname][self.nick] = [0, self]
		else:
			self.room[self.roomname] = {self.nick:[0, self]}
		print("room open")
		print(self.room)
		for x in self.room[self.roomname].keys():
			self.room[self.roomname][x][1].write_message(self.nick + '加入了聊天室')
			Nicklist = ''
			for i in self.room[self.roomname].keys():
				Nicklist += i + ' '
			self.room[self.roomname][x][1].write_message('NickList ' + Nicklist)

	def on_message(self, message):
		t2 = time.time()
		if self.room[self.roomname][self.nick][0]/(t2 - t1) > 1:
			self.room[self.roomname][self.nick][1].write_message('发送信息太快，请歇会儿。')
			print(self.roomname + "/" + self.nick + " too fast")
			return
		self.room[self.roomname][self.nick][0] += 1			
		a = message.split()
		b = ''
		for i in range(1, len(a)):
			b += a[i] + ' '
		if a[0] == "all":
			for x in self.room[self.roomname].keys():
				self.room[self.roomname][x][1].write_message(self.nick + ': ' + b)
		else:
			if a[0] == self.nick:
				self.room[self.roomname][a[0]][1].write_message(self.nick + ': ' + b)
			else:
				self.room[self.roomname][a[0]][1].write_message(self.nick + ': ' + b)
				self.room[self.roomname][self.nick][1].write_message(self.nick + ': ' + b)
		print("room message")
		print(self.room)

	def on_close(self):
		del self.room[self.roomname][self.nick]
		for x in self.room[self.roomname].keys():
			self.room[self.roomname][x][1].write_message(self.nick + '离开了聊天室')
			Nicklist = ''
			for i in self.room[self.roomname].keys():
				Nicklist += i + ' '
			self.room[self.roomname][x][1].write_message('NickList ' + Nicklist)
		if self.room[self.roomname] == {}:
			del self.room[self.roomname]
		print("room close")
		print(self.room)

class Index(tornado.web.RequestHandler):
    def get(self):
    	self.render('templates/main.html')
    def post(self):
    	print("r")
    	print(r)
    	if self.get_argument("room") in r.keys() and self.get_argument("nick") in r[self.get_argument("room")].keys():
    		self.write('你的nick已经被使用，请更换nick，重新<a href="">登录</a>。')
    	elif self.get_argument("nick")=="" or self.get_argument("room")=="":
    		self.write('房间名和昵称不能为空')	
    	elif len(self.get_argument("room")) > 20 or len(self.get_argument("nick")) > 20:
    		self.write('房间名称和用户名不能超过过20个字符，请重新<a href="">登录</a>。')
    	else:
    		self.render('templates/chat.html', room=self.get_argument("room"),nick=self.get_argument("nick"))

r = EchoWebSocket.room

if __name__ == '__main__':
	t1 = time.time()
	app = tornado.web.Application(
    		handlers=[('/', Index),('/websocket', EchoWebSocket)],
        	debug=True
        )
	app.listen(8000, address="0.0.0.0")
	tornado.ioloop.IOLoop.instance().start()